﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class QADocument : RibbonForm
    {
        public QADocument()
        {
            InitializeComponent();
        }

        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }

        void SearchQuarantinedItem(BRW_QUARANTINED.eSearch _eSearch)
        {
            BRW_QUARANTINED oSearcForm = new BRW_QUARANTINED();


            oSearcForm.ConnectionString = this.ConnectionString;
            oSearcForm.SearchOption = _eSearch;
            oSearcForm.ShowDialog();

            txtReference.Text = oSearcForm.Reference;
            txtCardCode.Text = oSearcForm.CardCode;
            txtCardName.Text = oSearcForm.CardName;
            txtItemCode.Text = oSearcForm.ItemCode;
            txtItemName.Text = oSearcForm.ItemName;
            txtUoM.Text = oSearcForm.UoM;
            txtQty.Text = oSearcForm.Qty;


            if (gridView1.RowCount == 0)
            {
                gridView1.AddNewRow();
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"], txtItemCode.Text);
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemName"], txtItemName.Text);
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UoM"], txtUoM.Text);
            }
        }

        public string Reference { get; set; }
        public string WarehouseCode { get; set; }
        public string WarehouseName { get; set; }
        public string VendorCode { get; set; }
        public string VendorName { get; set; }
        public string ItemCode { get; set; }
        public string ItemName { get; set; }
        public string UoM { get; set; }
        public string Quantity { get; set; }
        public string UnitPrice { get; set; }
        public string LotNumber { get; set; }
        public DateTime ExpiryDate { get; set; }
        public DateTime ManufacturingDate { get; set; }

        DataTable InitializeLineItems()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ItemCode", typeof(string));
            dt.Columns.Add("ItemName", typeof(string));
            dt.Columns.Add("UoM", typeof(string));
            dt.Columns.Add("Qty", typeof(string));           
            dt.Columns.Add("QAStatus", typeof(string));
            dt.Columns.Add("Location", typeof(string));
            dt.Columns.Add("LocationName", typeof(string));
            dt.Columns.Add("ControlNo", typeof(string));


            return dt;

        }

        void InitializeSeries()
        {

            string ObjectType = "300";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            
            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtDocNumber.Properties.ReadOnly = true;
                txtDocNumber.Text = "##########";

            }
            oSeries.Close();



        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = "300";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        public DataTable LineItems { get; set; }

        private void QADocument_Load(object sender, EventArgs e)
        {
            InitializeSeries();
            
            this.LineItems = InitializeLineItems();
            this.txtCreatedBy.Text = this.ActiveUserID;
            this.txtModifiedBy.Text = this.ActiveUserID;
            
            txtPostingDate.Text = System.DateTime.Now.ToString();
            txtDateCreated.Text = System.DateTime.Now.ToString();
            txtDateModified.Text = System.DateTime.Now.ToString();

            txtReference.Text = this.Reference;
            txtLocationCode.Text = this.WarehouseCode;
            txtLocationName.Text = this.WarehouseName;
            txtCardCode.Text =  this.VendorCode;
            txtCardName.Text = this.VendorName;
            txtItemCode.Text = this.ItemCode;
            txtItemName.Text = this.ItemName;
            txtUoM.Text = this.UoM;
            txtQty.Text = this.Quantity;
            txtLotNumber.Text = this.LotNumber;
            dtExpiryDate.EditValue = this.ExpiryDate;
            dtMfrDate.EditValue = this.ManufacturingDate;

            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();

            if (gridView1.RowCount <=0)
            {
                gridView1.AddNewRow();

                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"], txtItemCode.Text);
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemName"], txtItemName.Text);
                gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UoM"], txtUoM.Text);
            }

            
        }

        bool IsQuantityIsOver(string _QuantityToInsert)
        {
            Double Qty = Convert.ToDouble(txtQty.Text);
            Double _qtyInserted = 0; 

            foreach (DataRow oRow in this.LineItems.Rows)
            {
                if (!(oRow["Qty"] == DBNull.Value || oRow["Qty"].ToString() == ""))
                {
                    _qtyInserted = _qtyInserted + Convert.ToDouble(oRow["Qty"].ToString());
                }
            }

            //_qtyInserted = _qtyInserted + Convert.ToDouble(_QuantityToInsert);

            if (_qtyInserted > Qty)
            {
                return true;
            }
            else if (_qtyInserted <= Qty)
            {
                return false;
            }
            else
            {
                return false;
            }
        }

        bool IsItemComplete()
        {
            Double Qty = Convert.ToDouble(txtQty.Text);
            Double _qtyInserted = 0;

            foreach (DataRow oRow in this.LineItems.Rows)
            {
                _qtyInserted = _qtyInserted + Convert.ToDouble(oRow["Qty"].ToString());
            }

            if (_qtyInserted < Qty)
            {
                return false;
            }
            else if (_qtyInserted == Qty)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                gridView1.DeleteRow(gridView1.FocusedRowHandle);
            }
            if (e.KeyCode == Keys.Down)
            {
                if (gridView1.IsLastRow)
                {
                    string _QAStatus = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["QAStatus"]).ToString();
                    string _Qty = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"]).ToString();
                    string _ControlNo = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ControlNo"]).ToString();
                    if (_Qty != "" && _QAStatus != "" && _ControlNo !="")
                    {
                        if (IsItemComplete() == false)
                        {
                            gridView1.AddNewRow();

                            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemCode"], txtItemCode.Text);
                            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ItemName"], txtItemName.Text);
                            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UoM"], txtUoM.Text);
                        }
                    }
                }
            }
        }

        
        private void btnAdd_Click(object sender, EventArgs e)
        {

            QAManager oManager = new QAManager();
            QAUnit oUnit = new QAUnit(); // Used to passed the text box values

            //Header
            txtDocNumber.Text = GetNewSeries();
            
            
            oUnit.DocNumber = txtDocNumber.Text;
            oUnit.DocDate = Convert.ToDateTime(txtPostingDate.Text);
            oUnit.Remarks = txtRemarks.Text;           
            oUnit.Reference = txtReference.Text;
            oUnit.DocStatus = txtDocStatus.Text;

            
            oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
            oUnit.ModifiedBy = txtModifiedBy.Text;
            oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
            oUnit.CreatedBy = txtCreatedBy.Text;

            oUnit.LocationCode = txtLocationCode.Text;
            oUnit.LocationName = txtLocationName.Text;
            oUnit.CardCode = txtCardCode.Text;
            oUnit.CardName = txtCardName.Text;

            oUnit.ItemCode = txtItemCode.Text;
            oUnit.ItemName = txtItemName.Text;
            oUnit.UoM = txtUoM.Text;
            oUnit.Qty = Convert.ToDouble(txtQty.Text);
            oUnit.UnitPrice = Convert.ToDouble(this.UnitPrice);
            oUnit.LotNumber = txtLotNumber.Text;
            oUnit.ExpiryDate = (DateTime)dtExpiryDate.EditValue;
            oUnit.ManufacturingDate = (DateTime)dtMfrDate.EditValue;

            txtRemarks.Enabled = false;
            txtPostingDate.Enabled = false;
            //Line Items

            oUnit.LineItems = this.LineItems;

            try
            {
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();


                oManager.Add(oUnit); // PUSH TO SQL DATABASE

                oManager.ImportToStockCard(txtDocNumber.Text);

                oManager.ReleaseQuarantinedItem(txtReference.Text, txtCardCode.Text, txtItemCode.Text, txtLotNumber.Text);


                oManager.Close();


                btnAdd.Enabled = false;
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        private void txtQtyLineItem_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter)
            //{
            //    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit )sender;
            //    if (IsQuantityIsOver(oTextQty.Text))
            //    {
            //        MessageBox.Show("Over quantity is enter!!!!", "Over", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            //        oTextQty.Text = "0";
            //        oTextQty.Focus();
            //    }
            //}

            //if (e.KeyCode == Keys.Tab)
            //{
            //    DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;
            //    if (IsQuantityIsOver(oTextQty.Text))
            //    {
            //        MessageBox.Show("Over quantity is enter!!!!", "Over", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            //        oTextQty.Text = "0";
            //        oTextQty.Focus();
            //    }
            //}
        }

        private void txtQtyLineItem_Leave(object sender, EventArgs e)
        {
            try
            {
                DevExpress.XtraEditors.TextEdit oTextQty = (DevExpress.XtraEditors.TextEdit)sender;
                if (IsQuantityIsOver(oTextQty.Text))
                {
                    MessageBox.Show("Over quantity is enter!!!!", "Over", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    oTextQty.Text = "0";
                    oTextQty.Focus();

                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"], oTextQty.Text);
                }
            }
            catch
            {
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtLocCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_WHOUSE oFindWhse = new FND_WHOUSE();
            int iFocusHandle = gridView1.FocusedRowHandle;

            oFindWhse.ConnectionString = this.ConnectionString;
            oFindWhse.ShowDialog();

            gridView1.SetRowCellValue(iFocusHandle, gridView1.Columns["Location"], oFindWhse.WarehouseCode);
            gridView1.SetRowCellValue(iFocusHandle, gridView1.Columns["LocationName"], oFindWhse.WarehouseName);

        }
    }
}
